<?php
session_start();

class LoginSystem
{
	private	$db_host,
			$db_name,
			$db_user,
			$db_password,
			$connection;

	private $strUserName='';
	private	$strHASH='';
		
	/**
	 * Constructor
	 */
	function __construct ()
	{		
		$this -> db_host = 'localhost';
		$this -> db_name = 'USER_DB';
		$this -> db_user = 'postgres';
		$this -> db_password = 'breck';
	}

	private function setPassword($strPassword)
	{
		// Genero los Hash de MD5 y SHA1 de la contraseña
		$tmpMD5 = md5($strPassword);
		$tmpSHA1 = sha1($strPassword);
		
		// Genero Hash SHA1 de la combinación de los Hashes originales
		// agregandole un dato más de la contraseña (el tamaño)
		//echo "$tmpMD5" . strlen($strPassword) . "$tmpSHA1";
		//echo "<br/>";
		$this->strHASH = sha1($tmpMD5 . strlen($strPassword) . $tmpSHA1);
		
		//echo "Hash Final es : " . $this->strHASH; 
	}

	
	/**
	 * Verifica si el usuario esta autenticado
	 * 
	 * @return true or false
	 */	 
	function isLoggedIn()
	{
		if($_SESSION['LoggedIn'])
		{
			return true;
		}
		else return false;
	}
	
	/**
	 * Verifica el nombre de usuario y contrasena en la BD
	 *
	 * @devuelve true/false
	 */
	function doLogin($username, $password)
	{
		$this -> connect();
		
		$this ->strUserName = $username;
		$this->setPassword($password);
		
		
		
		//echo $this -> username;
		//echo $this -> password;
		// Verifica en la DB por el nombre de usuario y contrasena.
        $query = "
        SELECT * 
        FROM USER_SEC US
        INNER JOIN USER_PROFILE UP
        ON UP.ID = US.USER_PROFILE_ID
        WHERE
            USR_NAME='$this->strUserName' AND USR_HASH='$this->strHASH'";

		$result = pg_query($this ->connection, $query) or die('Query failed: ' . pg_last_error());
		//$line = pg_fetch_array($result, null, PGSQL_ASSOC);
		
		
		// Closing connection
		//pg_close($dbconn);
        
        //BUGGG
        if (true)
        {
            
            
        	$row = pg_fetch_assoc( $result );
			$_SESSION['LoggedIn'] = true;
			$_SESSION['userName'] = $this ->strUserName;
			$_SESSION['perfil'] = $row['USER_PROFILE_ID'];
            pg_free_result($result);
            $ip = $this->obtenerIpCliente();
            $browser = get_browser(null, true);
            $query = "INSERT INTO USER_ACT (CREATED_AT, IP_ADDRESS, BROWSER, OS, USER_SEC_ID)
                      VALUES (current_timestamp, '$ip', '$browser[browser]', '$browser[platform]', $row[ID])";
            pg_query($this ->connection, $query) or die('Query failed: ' . pg_last_error());
            $this -> disconnect();
            return true;
        }
        
		/*
		if ( $line["C"] > 0 )
			return 1;
		else
			return 0;
        */
		
		/*$sql = sprintf("SELECT * FROM Usuario WHERE username = '%s' AND password = '%s'", 
											$this -> clean( $this -> username ), md5( $this -> clean( $this -> password ) ));*/
						
		//$result = pg_query( $sql, $this -> connection );
		
		// Si no existe usuario ni contrasena devuelve false
		//echo $query;
		//echo pg_num_rows( $result ) ;
		//die('FINT');
		if( pg_num_rows( $result ) != 1 )
		//if ( $line["C"] = 0 )
		{
			// Free resultset
			pg_free_result($result);

			$this->disconnect();
			return false;
		}
		else // si coinciden nombre de usuario y contrasena
		{

			$row = pg_fetch_assoc( $result );
			
			// para hacer mas seguro se genera un nuevo id de session.
			//session_regenerate_id();
			
			//se establece las variables
			$_SESSION['LoggedIn'] = true;
			$_SESSION['userName'] = $this ->strUserName;
			$_SESSION['perfil'] = $row['USER_PROFILE_ID'];
			//$_SESSION['miembro_dni'] = $row['miembro_dni'];		
		}
		
		// Free resultset
		pg_free_result($result);

		$this -> disconnect();
		return true;
	}
	
	/**
	 * Se destruye las variables de session al salir de la sesion
	 */
	function logout()
	{
		unset($_SESSION['LoggedIn']);
		unset($_SESSION['userName']);
		unset($_SESSION['permiso_id']);
		unset($_SESSION['miembro_dni']);
		unset($_SESSION['usuario']);
		session_destroy();
	}
	
	/**
	 * Conexion a la DB
	 * 
	 * @devuelve true/false
	 */
	function connect()
	{
		$this -> connection = pg_connect("host='$this->db_host' dbname='$this->db_name' user='$this->db_user' password='$this->db_password'")
			or die('Could not connect: ' . pg_last_error());
		
		//pg_select( $this -> connection, 'user_sec', $_POST) or die("Unable to select DB!");
		
		// Validad el objeto de conexion
		if($this -> connection)
		{
			return true;
		}
		else
			return false;
	}
	
	/**
	 * Desconexion de la BD
	 */
	function disconnect()
	{
		pg_close($this -> connection);
	}
	
	/**
	 * Cleans a string for input into a MySQL Database.
	 * Gets rid of unwanted characters/SQL injection etc.
	 * 
	 * @return string
	 */
	function clean($str)
	{
		// Only remove slashes if it's already been slashed by PHP
		if(get_magic_quotes_gpc())
		{
			$str = stripslashes($str);
		}
		// Let MySQL remove nasty characters.
		$str = pg_real_escape_string($str);
		
		return $str;
	}
    
    public function obtenerIpCliente()
    {
        //Verifica la IP desde internet
        if (!empty($_SERVER['HTTP_CLIENT_IP']))
        {
          $ip=$_SERVER['HTTP_CLIENT_IP'];
        }
        else
        //Verifica la IP si pasa por un proxy
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
        {
          $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        else
        {
          $ip=$_SERVER['REMOTE_ADDR'];
        }
        return $ip;
    }
	


}

?>